package org.myhomework.servelet;

import org.myhomework.constant.Constants;
import org.myhomework.dao.TeacherDao;
import org.myhomework.dao.UserDao;
import org.myhomework.entity.Teacher;
import org.myhomework.entity.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ChangeInfoServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer id;
        if (null != req.getParameter("id")) {
            if (!checkPermission(req, resp)) {
                return;
            }
            id = Integer.parseInt(req.getParameter("id"));
        } else {
            id = (Integer) req.getSession().getAttribute(Constants.USER_ID_ATTRIBUTE);
        }
        Teacher teacher = TeacherDao.getByUserId(id);
        req.setAttribute("teacher", teacher);
        req.setAttribute("back", req.getParameter("back"));
        req.getRequestDispatcher("/change-info.jsp").forward(req, resp);
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer id = Integer.parseInt(req.getParameter("id"));
        Integer age = Integer.parseInt(req.getParameter("age"));
        String sex = req.getParameter("sex");
        String school = req.getParameter("school");
        String course = req.getParameter("course");
        String name = req.getParameter("name");
        Teacher teacher = new Teacher();
        teacher.setName(name);
        teacher.setId(id);
        teacher.setAge(age);
        teacher.setCourse(course);
        teacher.setSchool(school);
        teacher.setSex(sex);
        TeacherDao.updateById(teacher);
        req.setAttribute("back", req.getParameter("back"));
        req.setAttribute("msg", "更新成功");
        req.getRequestDispatcher("/ok.jsp").forward(req, resp);
    }

    private boolean checkPermission(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Integer userId = (Integer) req.getSession().getAttribute(Constants.USER_ID_ATTRIBUTE);
        User user = UserDao.getById(userId);
        if (Constants.ADMIN_TYPE != user.getType()) {
            resp.getWriter().write("无权访问");
            return false;
        }
        return true;
    }
}
